package day17;

import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.File;
import java.util.*;

/**
 * @author Xiao
 * @date 2021/8/12
 */
public class XMLDemo01 {
    /**
     * 解析country.xml文件
     * 将解析后的province信息存储到ArrayList集合中，遍历集合。
     */
    public static void main(String[] args) throws DocumentException {
        //创建SAXReader对象
        SAXReader saxReader = new SAXReader();
        //加载xml文件
        Document document = saxReader.read(new File(
                "classpractice/src/day17/country.xml"));
        //获取根目录
        Element country = document.getRootElement();
        //获取所有省份
        List<Element> elements = country.elements();
        Element provinceHunan = elements.get(0);
        Element provinceHuBei = elements.get(1);
        //获取省份的名字
        Attribute attributeHunan = provinceHunan.attribute("name");
        Attribute attributeHubei = provinceHuBei.attribute("name");
        String nameHunan = attributeHunan.getValue();
        String nameHubei = attributeHubei.getValue();
        //创建两个TreeMap集合，用于存储城市信息
        TreeMap<String, String> tmHunan = new TreeMap<>();
        TreeMap<String, String> tmHuBei = new TreeMap<>();
        //将城市信息添加至TreeMap集合中的方法
        getTreeMap(tmHunan, provinceHunan);
        getTreeMap(tmHuBei, provinceHuBei);
        //打印省份名字和城市信息
        System.out.print(nameHunan + ":\t");
        System.out.println(tmHunan.values());
        System.out.print(nameHubei + ":\t");
        System.out.println(tmHuBei.values());
    }

    /**将各个城市信息添加到TreeMap集合中的方法*/
    private static void getTreeMap(TreeMap<String, String> tmHunan, Element provinceHunan) {
        //获取各个城市的信息集合
        List<Element> elements = provinceHunan.elements();
        //遍历城市集合
        for (Element city : elements) {
            //获取城市id
            Attribute idAttribute = city.attribute("id");
            String id = idAttribute.getValue();
            //获取城市name
            String name = city.getText();
            //将id和name添加到TreeMap集合中
            tmHunan.put(id, name);
        }
    }
}
